<?php

/**
 * ProductController
 */
class ProductController extends CustomControllerBase {
	/**
	 *
	 * SystemCategoryDataService Object
	 * @var SystemCategoryDataService
	 */
	public $systemCategoryDataService = null;
	
	/**
	 *
	 * UserManufacturerDataService Object
	 * @var UserManufacturerDataService Object
	 */
	public $userManufacturerDataService = null;
	
	/**
	 *
	 * UserCustomerBasketDataService Object
	 * @var UserCustomerBasketDataService Object
	 */
	public $userCustomerBasketDataService = null;
	
	/**
	 * AddressDataService Object
	 * @var AddressDataService Object
	 */
	private $addressDataService = null;
	
	/**
	 * CustomerOrderDataService Object
	 * @var CustomerOrderDataService Object
	 */
	private $customerOrderDataService = null;
	
	/**
	 * CustomerOrderProductDataService Object
	 * @var CustomerOrderProductDataService Object
	 */
	private $customerOrderProductDataService = null;
	
	/**
	 * OrderStatusHistoryDataService Object
	 * @var OrderStatusHistoryDataService Object
	 */
	private $orderStatusHistoyDataService = null;
	
	/**
	 * Constructor of index
	 */
	public function __construct() {
		parent::__construct ();
		
		// Set page name
		$this->setPageName ( 'user_product' );
		$this->setModuleName ( "Product" );
		
		//Check if Blogging Module is enabled
		if ($this->currentPackageOption) {
			$module = MODULE_ECOMMERCE;
			$isEnabled = $this->currentPackageOption->isEnabled ( $module );
			
			if ($isEnabled == false) {
				$url = $this->getApplicationUrl ();
				CommonUtils::redirect ( $url );
				return - 1;
			}
		}
		
		// Initialise userProductDataService
		$this->systemCategoryDataService = new SystemCategoryDataService ();
		$this->userManufacturerDataService = new UserManufacturerDataService ();
		$this->userCustomerBasketDataService = new UserCustomerBasketDataService ();
		$this->addressDataService = new AddressDataService ();
		$this->customerOrderDataService = new CustomerOrderDataService ();
		$this->customerOrderProductDataService = new CustomerOrderProductDataService ();
		$this->orderStatusHistoyDataService = new OrderStatusHistoryDataService ();
		
		// Get list category
		$arrElement = array ();
		$arrElement ['ownerId'] = $this->ownerId;
		$arrElement ['type'] = CATEGORY_PRODUCT;
		
		$catList = $this->systemCategoryDataService->getItems ( $arrElement );
		$this->smarty->assign ( 'catList', $catList );
		$this->smarty->assign ( 'catListCount', count ( $catList ) );
		
		if ($this->authentication->getCurrentUserId () != "" && $this->authentication->getSession ()->userType == ROLE_MEMBER_USER) {
			$arrElement = array ();
			$arrElement ['customerId'] = $this->authentication->getCurrentUserId ();
			
			//Refresh list of cart items
			$cartList = $this->userCustomerBasketDataService->getItems ( $arrElement );
			$countCartList = $this->userCustomerBasketDataService->getTotals ( $arrElement );
			$this->smarty->assign ( 'currentCartList', $cartList );
			$this->smarty->assign ( 'countCurrentCartList', $countCartList );
		}
		
		// Load Payment Information
		$this->loadAllPayment ( $this->ownerId );
	
	}
	
	/**
	 * The "index" action is the default action for all controllers -- the
	 * landing page of the site.
	 *
	 * @return void
	 *
	 */
	public function indexAction() {
		// Get 5 latest Product entry
		$arrElement = array ();
		$arrElement ['status'] = UserProductEntity::ACTIVE;
		$arrElement ['ownerId'] = $this->ownerId;
		$cat = $this->getQuery ( 'cat' );
		if ($cat != "") {
			$arrElement ['categoryId'] = $cat;
		}
		
		$manufacturerId = $this->getQuery ( 'mnu' );
		if ($manufacturerId != "") {
			$arrElement ['manufacturerId'] = $manufacturerId;
		}
		
		$numRecordPerPage = ITEM_PER_PAGE;
		
		// Pager
		$start = $this->getQuery ( 'start', 0 );
		if ($start == '' || $start < 0) {
			$start = 0;
		}
		
		// Get total records of product options based on search criterias
		$totals = $this->userProductDataService->getTotals ( $arrElement );
		
		$itemsList = $this->userProductDataService->getItems ( $arrElement, " id DESC", $start, $numRecordPerPage );
		if ($start > $totals) {
			$start = 0;
		}
		//$link = Zend_Registry::get('config')->APPLICATION_URL .'/'. $this->ownerName ."/Product/Index";
		$link = $this->getApplicationUrl () . "Product/Index";
		$link .= $cat != '' ? "/cat/{$cat}" : '';
		$pageLink = '';
		if ($totals > $numRecordPerPage) {
			$pageUtils = new PagerUtils ( $start, $totals, $numRecordPerPage, 10, $link );
			$pageLink = $pageUtils->writePagesLinks ( 2, 'start' );
			$pageLink .= "<br><span class=\"paing_text_nolink\">" . $pageUtils->writePagesCounter () . "</span>";
		}
		
		$this->smarty->assign ( 'productItemList', $itemsList );
		$this->smarty->assign ( 'pageLink', $pageLink );
		$this->smarty->assign ( 'numberProductItemList', count ( $itemsList ) );
		
		//Get Manufacturer List
		$arrElement = array ();
		$arrElement ['ownerId'] = $this->ownerId;
		$manufacturerList = $this->userManufacturerDataService->getItems ( $arrElement );
		$this->smarty->assign ( 'manufacturerList', $manufacturerList );
		
		if ($this->isMobileMode == false) {
			// Assign Smarty Content
			$this->assignSmartyContent ( 'Product/product_list.tpl' );
		} else {
			$this->assignSmartyMobileContent ( 'Product/m_product_list.tpl' );
		}
	
		//$this->smarty->assign('SMARTY_CONTENT_PATH', 'template1/Product/product_list.tpl');
	//$this->smarty->display(APPLICATION_PATH . '/Layouts/template1/MainLayout.tpl');
	}
	
	/**
	 * Product Details Action
	 */
	public function detailsAction() {
		$this->setPageName ( 'user_product_details' );
		$id = $this->getQuery ( 'id' );
		if ($id == '') {
			$id = $this->getPost ( 'id', '' );
		}
		
		$id = intval ( $id );
		// Get data
		$userProductEntity = $this->userProductDataService->getById ( $id );
		if (empty ( $userProductEntity )) {
			// Go on to login page
			//$url = Zend_Registry::get('config')->APPLICATION_URL . "/" . $this->ownerName . "/Product";
			$url = $this->getApplicationUrl () . "Product";
			CommonUtils::redirect ( $url );
			return - 1;
		}
		
		// Check valid Product Owner
		if ($this->ownerId != $userProductEntity->ownerId) {
			// Invalid Product
			$url = $this->getApplicationUrl () . "Product";
			//CommonUtils::redirect($url);
			return - 1;
		}
		
		$this->smarty->assign ( 'productEntity', $userProductEntity );
		$this->smarty->assign ( 'tax', $userProductEntity->getTax () );
		$this->smarty->assign ( 'id', $id );
		
		$this->setMetaDescription ( $userProductEntity->metaDescription );
		$this->setPageTitle ( $userProductEntity->metaTitle );
		$this->setMetaKeywords ( $userProductEntity->metaKeywords );
		
		if ($this->isMobileMode == false) {
			// Assign Smarty Content
			$this->assignSmartyContent ( 'Product/product_details.tpl' );
		} else {
			$this->assignSmartyMobileContent ( 'Product/m_product_details.tpl' );
		}
	
		//$this->smarty->assign('SMARTY_CONTENT_PATH', 'template1/Product/product_details.tpl');
	//$this->smarty->display(APPLICATION_PATH . '/Layouts/template1/MainLayout.tpl');
	}
	
	/**
	 * Checkout Action
	 */
	public function checkoutShippingAction() {
		$error = "";
		
		//Check login user
		$this->requireUserLogin ();
		
		// Get Main Address of Customer
		$mainAddressId = $this->authentication->getSession ()->mainAddressId;
		$mainAddress = $this->addressDataService->getById ( $mainAddressId );
		if (empty ( $mainAddress )) {
			$error = "Your address is empty. Please update it so that we can buy/sell products";
		}
		//Update Shipping Address
		$customerSession = $this->authentication->getCustomerOrderSession ();
		
		if ($customerSession->shippingAddressId == - 1) {
			$customerSession->shippingAddressId = $mainAddressId;
		}
		//Update Shipping Address
		if ($customerSession->billingAddressId == - 1) {
			$customerSession->billingAddressId = $mainAddressId;
		}
		$this->authentication->saveCustomerOrderSession ( $customerSession );
		
		$shippingAddress = $this->addressDataService->getById ( $customerSession->shippingAddressId );
		
		$userShipDataService = new UserShipDataService ();
		$listShipMethod = $userShipDataService->getAllShipMethodByUser ( $this->ownerId );
		
		// Get Details
		$actionForm = $this->getPost ( 'actionForm' );
		
		if (! empty ( $actionForm ) && $actionForm == 'submit') {
			//Update information of SESSION
			$customerSession = $this->authentication->getCustomerOrderSession ();
			$comment = $this->getPost ( 'comment', '' );
			$shippingMethod = $this->getPost ( 'shipmethod', '0' );
			$customerSession->comment = $comment;
			$customerSession->shippingMethod = $shippingMethod;
			$this->authentication->saveCustomerOrderSession ( $customerSession );
			
			//Redirect to Shipping information
			//$url = Zend_Registry::get('config')->APPLICATION_URL . '/' . $this->ownerName . "/Product/checkoutPayment";
			$url = $this->getApplicationUrl () . "Product/checkoutPayment";
			CommonUtils::redirect ( $url );
			return - 1;
		}
		
		$this->smarty->assign ( 'mainAddress', $mainAddress );
		$this->smarty->assign ( 'comment', $customerSession->comment );
		$this->smarty->assign ( 'shippingAddress', $shippingAddress );
		$this->smarty->assign ( 'errorMessage', ! empty ( $error ) ? $error : '' );
		$this->smarty->assign ( 'listItem', $listShipMethod );
		
		// Get Shipping Method and Shipping Fee
		$shippingFeeSettingEntity = $this->settingsDataService->getItem ( SETTINGS_SHIPPING_FEE, $this->ownerId );
		$shippingMethodSettingEntity = $this->settingsDataService->getItem ( SETTINGS_SHIPPING_METHOD, $this->ownerId );
		
		$this->smarty->assign ( 'shipping_method', $shippingMethodSettingEntity->value );
		$this->smarty->assign ( 'shipping_fee', $shippingFeeSettingEntity->value );
		
		if ($this->isMobileMode == false) {
			// Assign Smarty Content
			$this->assignSmartyContent ( 'Product/checkout_shipping.tpl' );
		} else {
			$this->assignSmartyMobileContent ( 'Product/m_checkout_shipping.tpl' );
		}
	
		//$this->smarty->assign('SMARTY_CONTENT_PATH', 'template1/Product/checkout_shipping.tpl');
	//$this->smarty->display(APPLICATION_PATH . '/Layouts/template1/MainLayout.tpl');
	}
	
	/**
	 * Add to Cart this product
	 */
	public function addCartAction() {
		//Check login user
		$this->requireUserLogin ();
		
		// Get Product Add to Cart
		$id = $this->getQuery ( 'id' );
		if ($id == '') {
			$id = $this->getPost ( 'id', '' );
		}
		
		$productEntity = $this->userProductDataService->getById ( $id );
		
		if (intval ( $id ) == 0 || empty ( $productEntity )) {
			//$url = Zend_Registry::get('config')->APPLICATION_URL . '/' . $this->ownerName . "/Product";
			$url = $this->getApplicationUrl () . "Product";
			CommonUtils::redirect ( $url );
			return - 1;
		}
		
		// Check valid Product Owner
		if ($this->ownerId != $productEntity->ownerId) {
			// Invalid Product
			$url = $this->getApplicationUrl () . "Product";
			CommonUtils::redirect ( $url );
			return - 1;
		}
		
		$arrElement = array ();
		$arrElement ['customerId'] = $this->authentication->getCurrentUserId ();
		$arrElement ['productId'] = $id;
		$cartList = $this->userCustomerBasketDataService->getItems ( $arrElement );
		if (count ( $cartList ) > 0) {
			//Exist in Shopping Cart
			$cartItem = $cartList [0];
			$cartItem->quantity = $cartItem->quantity + 1;
			$cartItem->finalPrice = $productEntity->price * $cartItem->quantity;
			$this->userCustomerBasketDataService->update ( $cartItem );
		} else {
			//Add new Product to Cart
			$cartItem = $this->userCustomerBasketDataService->beforeCreate ();
			$cartItem->customerId = $this->authentication->getCurrentUserId ();
			$cartItem->productId = $id;
			$cartItem->quantity = 1;
			$cartItem->finalPrice = $productEntity->price;
			$cartItem->addedDate = date ( "Y-m-d" );
			$this->userCustomerBasketDataService->create ( $cartItem );
		}
		
		//$url = Zend_Registry::get('config')->APPLICATION_URL . '/' . $this->ownerName . "/Product/shoppingCart";
		$url = $this->getApplicationUrl () . "Product/shoppingCart";
		CommonUtils::redirect ( $url );
		return - 1;
	}
	
	/**
	 * Checking Shopping Cart
	 */
	public function shoppingCartAction() {
		//Check login user
		$this->requireUserLogin ();
		$arrElement = array ();
		$arrElement ['customerId'] = $this->authentication->getCurrentUserId ();
		//Refresh list of cart items
		$cartList = $this->userCustomerBasketDataService->getItems ( $arrElement );
		$countCartList = $this->userCustomerBasketDataService->getTotals ( $arrElement );
		$this->smarty->assign ( 'cartList', $cartList );
		$this->smarty->assign ( 'countCartList', $countCartList );
		
		if ($this->isMobileMode == false) {
			// Assign Smarty Content
			$this->assignSmartyContent ( 'Product/shopping_cart.tpl' );
		} else {
			$this->assignSmartyMobileContent ( 'Product/m_shopping_cart.tpl' );
		}
	}
	
	/**
	 * Remove Cart Action
	 */
	public function removeCartAction() {
		//Check login user
		$this->requireUserLogin ();
		
		// Get Product Add to Cart
		$id = $this->getQuery ( 'id' );
		if ($id == '') {
			$id = $this->getPost ( 'id', '' );
		}
		
		$productEntity = $this->userProductDataService->getById ( $id );
		if (intval ( $id ) == 0 || empty ( $productEntity )) {
			//$url = Zend_Registry::get('config')->APPLICATION_URL . '/' . $this->ownerName . "/Product";
			$url = $this->getApplicationUrl () . "Product";
			CommonUtils::redirect ( $url );
			return - 1;
		}
		
		$this->userCustomerBasketDataService->removeCart ( $this->authentication->getCurrentUserId (), $productEntity->id );
		
		//$url = Zend_Registry::get('config')->APPLICATION_URL . '/' . $this->ownerName . "/Product/shoppingCart";
		$url = $this->getApplicationUrl () . "Product/shoppingCart";
		CommonUtils::redirect ( $url );
		return - 1;
	}
	
	/**
	 * Update Shopping Cart Action
	 */
	public function updateCartAction() {
		//Check login user
		$this->requireUserLogin ();
		
		$actionForm = $this->getPost ( 'actionForm' );
		if (! empty ( $actionForm ) && $actionForm == 'submit') {
			$totals = $this->getPost ( 'totals' );
			if ($totals > 0) {
				$arrElement = array ();
				$arrElement ['customerId'] = $this->authentication->getCurrentUserId ();
				$cartList = $this->userCustomerBasketDataService->getItems ( $arrElement );
				
				for($i = 0; $i < $totals; $i ++) {
					$quantityName = "quantity" . $i;
					$quantiy = $this->getPost ( $quantityName );
					
					$cartItem = $cartList [$i];
					$productEntity = $cartItem->getProduct ();
					// Check valid Product Owner
					if ($this->ownerId != $productEntity->ownerId) {
						// Invalid Product
						$url = $this->getApplicationUrl () . "Product";
						CommonUtils::redirect ( $url );
						return - 1;
					}
					
					if ($quantiy > 0) {
						// Update the quantity of this product
						$cartItem->quantity = $quantiy;
						$cartItem->finalPrice = $productEntity->price * $quantiy;
						$this->userCustomerBasketDataService->update ( $cartItem );
					} else {
						//Remove this item
						$this->userCustomerBasketDataService->removeCart ( $this->authentication->getCurrentUserId (), $cartItem->productId );
					}
				}
			}
		}
		
		//$url = Zend_Registry::get('config')->APPLICATION_URL . '/' . $this->ownerName . "/Product/shoppingCart";
		$url = $this->getApplicationUrl () . "Product/shoppingCart";
		CommonUtils::redirect ( $url );
		return - 1;
	}
	
	/**
	 *
	 * Checkout Payment Action
	 */
	public function checkoutPaymentAction() {
		$error = "";
		//Check login user
		$this->requireUserLogin ();
		
		// Get Main Address of Customer
		$mainAddressId = $this->authentication->getSession ()->mainAddressId;
		$mainAddress = $this->addressDataService->getById ( $mainAddressId );
		if (! $mainAddress) {
			$error = "Your address is empty. Please update it so that we can buy/sell products";
		}
		
		//Update Shipping Address
		$customerSession = $this->authentication->getCustomerOrderSession ();
		if ($customerSession->shippingAddressId == - 1) {
			$customerSession->shippingAddressId = $mainAddressId;
		}
		//Update Shipping Address
		if ($customerSession->billingAddressId == - 1) {
			$customerSession->billingAddressId = $mainAddressId;
		}
		$this->authentication->saveCustomerOrderSession ( $customerSession );
		
		$billingAddress = $this->addressDataService->getById ( $customerSession->billingAddressId );
		
		// Get Details
		$actionForm = $this->getPost ( 'actionForm' );
		if (! empty ( $actionForm ) && $actionForm == 'submit') {
			//Update information of SESSION
			$customerSession = $this->authentication->getCustomerOrderSession ();
			$comment = $this->getPost ( 'comment', '' );
			$payment = $this->getPost ( 'paymentMethod', '' );
			$customerSession->comment = $comment;
			$customerSession->paymentMethod = $payment;
			$this->authentication->saveCustomerOrderSession ( $customerSession );
			
			//Redirect to Shipping information
			//$url = Zend_Registry::get('config')->APPLICATION_URL . '/' . $this->ownerName . "/Product/confirmOrder";
			$url = $this->getApplicationUrl () . "Product/confirmOrder";
			CommonUtils::redirect ( $url );
		
		}
		
		// Get all enable payment methods
		//$this->loadAllPayment($this->ownerId);
		

		$this->smarty->assign ( 'mainAddress', $mainAddress );
		$this->smarty->assign ( 'billingAddress', $billingAddress );
		$this->smarty->assign ( 'comment', $customerSession->comment );
		$this->smarty->assign ( 'errorMessage', ! empty ( $error ) ? $error : '' );
		
		if ($this->isMobileMode == false) {
			// Assign Smarty Content
			$this->assignSmartyContent ( 'Product/checkout_payment.tpl' );
		} else {
			$this->assignSmartyMobileContent ( 'Product/m_checkout_payment.tpl' );
		}
	}
	
	/*
	 * Confirm Order before go to payment
	 */
	public function confirmOrderAction() {
		//Check login user
		$this->requireUserLogin ();
		
		$customerSession = $this->authentication->getCustomerOrderSession ();
		// Check if there's exist an previous order
		unset ( $arrElement );
		$arrElement = array ();
		$arrElement ['customers_id'] = $this->authentication->getCurrentUserId ();
		$arrElement ['orders_status'] = ORDER_STATUS_EDITING;
		$results = $this->customerOrderDataService->getItems ( $arrElement );
		if (count ( $results ) > 0) {
			$customerOrder = $results [0];
			$customerOrder->payment_method = $customerSession->paymentMethod;
			$customerOrder->last_modified = date ( "Y-m-d H:i:s" );
			$this->customerOrderDataService->update ( $customerOrder );
			$customerOrderId = $customerOrder->id;
			$customerOrder->currency = $this->currencyCode;
			$customerOrder->shipping_method = $customerSession->shippingMethod;
		
		} else {
			// Create a new Customer Order
			$customerOrder = $this->customerOrderDataService->beforeCreate ();
			$customerOrder->updateCustomerAddress ( $this->authentication->getCurrentUserId () );
			$customerOrder->updateBillingAddress ( $customerSession->billingAddressId );
			$customerOrder->updateShippingAddress ( $customerSession->shippingAddressId );
			$customerOrder->payment_method = $customerSession->paymentMethod;
			$customerOrder->orders_status = ORDER_STATUS_EDITING;
			$customerOrder->date_purchased = date ( "Y-m-d H:i:s" );
			$customerOrder->last_modified = date ( "Y-m-d H:i:s" );
			$customerOrder->shipping_method = $customerSession->shippingMethod;
			$customerOrder->currency = $this->currencyCode;
			$customerOrderId = $customerOrder->id = $this->customerOrderDataService->create ( $customerOrder );
		
		}
		
		// Get Product Customer Bastket
		unset ( $arrElement );
		$arrElement = array ();
		$arrElement ['customerId'] = $this->authentication->getCurrentUserId ();
		//Refresh list of cart items
		$cartList = $this->userCustomerBasketDataService->getItems ( $arrElement );
		$countCartList = $this->userCustomerBasketDataService->getTotals ( $arrElement );
		
		$userShipDataService = new UserShipDataService ();
		$shippingMethod = $userShipDataService->getById ( $customerSession->shippingMethod );
		$this->smarty->assign ( 'shippingMethod', $shippingMethod );
		
		$actionForm = $this->getPost ( 'actionForm', '' );
		if (! empty ( $actionForm ) && $actionForm == 'submit') {
			//Do redirect to Payment method
			$paymentMethod = $customerSession->paymentMethod;
			
			if ($paymentMethod == PAYMENT_GOOGLECHECKOUT) {
				//Currently just save the Customer Order				
				$customerOrder->orders_status = ORDER_STATUS_PENDING;
				$this->customerOrderDataService->update ( $customerOrder );
				foreach ( $cartList as $cartItem ) {
					$this->customerOrderProductDataService->addProduct ( $customerOrder->id, $cartItem );
				}
				$this->userCustomerBasketDataService->removeCart ( $this->authentication->getCurrentUserId (), NULL );
				
				// Google Checkout Payment Gateway
				$this->handleGoogleCheckout ( $cartList, $customerOrderId, $this->authentication->getCurrentUserId (), $shippingMethod );
			} else if ($paymentMethod == PAYMENT_PAYPAL) {
				$customerOrder->orders_status = ORDER_STATUS_PENDING;
				$this->customerOrderDataService->update ( $customerOrder );
				foreach ( $cartList as $cartItem ) {
					$this->customerOrderProductDataService->addProduct ( $customerOrder->id, $cartItem );
				}
				$this->userCustomerBasketDataService->removeCart ( $this->authentication->getCurrentUserId (), NULL );
				
				// Paypal Payment Gateway
				$this->handlePaypal ( $cartList, $customerOrderId, $this->authentication->getCurrentUserId (), $shippingMethod );
				return - 1;
			} else if ($paymentMethod == PAYMENT_2CHECKOUT) {
				$customerOrder->orders_status = ORDER_STATUS_PENDING;
				$this->customerOrderDataService->update ( $customerOrder );
				foreach ( $cartList as $cartItem ) {
					$this->customerOrderProductDataService->addProduct ( $customerOrder->id, $cartItem );
				}
				
				$this->userCustomerBasketDataService->removeCart ( $this->authentication->getCurrentUserId (), NULL );
				
				// 2Checkout Payment Gateway
				$this->_submit2Checkout ( $cartList, $customerOrder, $shippingMethod );
				return - 1;
			} else {
				if ($paymentMethod == PAYMENT_EWAY) {
					$customerOrder->orders_status = ORDER_STATUS_PENDING;
					$this->customerOrderDataService->update ( $customerOrder );
					foreach ( $cartList as $cartItem ) {
						$this->customerOrderProductDataService->addProduct ( $customerOrder->id, $cartItem );
					}
					
					$this->userCustomerBasketDataService->removeCart ( $this->authentication->getCurrentUserId (), NULL );
					
					$this->_handleEway ( $cartList, $customerOrder, $shippingMethod );
				}
			}
			
			//Currently just save the Customer Order
			$customerOrder->orders_status = ORDER_STATUS_PENDING;
			
			//$customerOrder->orders_status = ORDER_STATUS_PROCESSING;
			$this->customerOrderDataService->update ( $customerOrder );
			
		/*
			 //Clear all Data on Basket
			 $this->userCustomerBasketDataService->removeCart($this->authentication->getCurrentUserId(), NULL);

			 //Add Product Order Status History
			 $orderStatusHistoryDataService = new OrderStatusHistoryDataService();
			 $orderHistory = $orderStatusHistoryDataService->beforeCreate();
			 $orderHistory->orders_id = $customerOrder->id;
			 $orderHistory->orders_status = ORDER_STATUS_PENDING;
			 $orderHistory->date_added = date("Y-m-d H:i:s");
			 $orderHistory->comments = $customerSession->comment;
			 $orderStatusHistoryDataService->create($orderHistory);

			 //Clear the SESSION
			 $customerSession->shippingAddressId = -1;
			 $customerSession->billingAddressId = -1;
			 $customerSession->comment = "";
			 $this->authentication->saveCustomerOrderSession($customerSession);

			 //Redirect to success customer order
			 //$url = Zend_Registry::get('config')->APPLICATION_URL . '/' . $this->ownerName . "/Product/orderSuccess";
			 $url = $this->getApplicationUrl() . "Product/orderSuccess";
			 CommonUtils::redirect($url);
			 return -1;
			 */
		}
		
		//Get Shipping Address
		$shippingAddress = $this->addressDataService->getById ( $customerSession->shippingAddressId );
		
		// Get Billing Address
		$billingAddress = $this->addressDataService->getById ( $customerSession->billingAddressId );
		
		// Get Payment Methods
		$paymentMethod = $customerSession->paymentMethod;
		
		// Get Shipping Method and Shipping Fee
		//$shippingFeeSettingEntity = $this->settingsDataService->getItem(SETTINGS_SHIPPING_FEE, $this->ownerId);
		//$shippingMethodSettingEntity = $this->settingsDataService->getItem(SETTINGS_SHIPPING_METHOD, $this->ownerId);
		

		//$this->smarty->assign('shipping_method', $shippingMethodSettingEntity->value);
		//$this->smarty->assign('shipping_fee', $shippingFeeSettingEntity->value);
		

		// get Comment
		$comment = $customerSession->comment;
		
		// Assign Values Data
		$this->smarty->assign ( 'shippingAddress', $shippingAddress );
		$this->smarty->assign ( 'billingAddress', $billingAddress );
		$this->smarty->assign ( 'paymentMethod', $paymentMethod );
		$this->smarty->assign ( 'comment', $comment );
		$this->smarty->assign ( 'cartList', $cartList );
		
		// Assign Error Information
		$this->smarty->assign ( 'isError', $this->isError );
		$this->smarty->assign ( 'error', $this->error );
		
		if ($this->isMobileMode == false) {
			// Assign Smarty Content
			$this->assignSmartyContent ( 'Product/checkout_confirm.tpl' );
		} else {
			$this->assignSmartyMobileContent ( 'Product/m_checkout_confirm.tpl' );
		}
	}
	
	/**
	 *
	 * Checkout Order Successfully
	 */
	public function orderSuccessAction() {
		if ($this->isMobileMode == false) {
			// Assign Smarty Content
			$this->assignSmartyContent ( 'Product/checkout_success.tpl' );
		} else {
			$this->assignSmartyMobileContent ( 'Product/m_checkout_success.tpl' );
		}
	
		//$this->smarty->assign('SMARTY_CONTENT_PATH', 'template1/Product/checkout_success.tpl');
	//$this->smarty->display(APPLICATION_PATH . '/Layouts/template1/MainLayout.tpl');
	}
	
	/**
	 * Handle GoogleCheckout Payment Gateway
	 * @param array $cartList
	 * @param int $orderId: order Id
	 * @param int $customerId: customer ID
	 * @param UserShipEntity $shippingMethod: Shipping Method
	 */
	private function handleGoogleCheckout($cartList, $orderId, $customerId, $shippingMethod) {
		// Get Google Checkout Configuration
		

		$isError = false;
		$config = $this->settingsDataService->getGoogleCheckoutSettings ( $this->ownerId );
		if (isset ( $config ['merchantId'] ) && isset ( $config ['enable'] ) && $config ['enable'] == true) {
			
			$merchant_id = $config ['merchantId']; // Your Merchant ID
			$merchant_key = $config ['merchantKey']; // Your Merchant Key
			$server_type = $config ['server_type'];
			$currency = "USD";
			$cart = new GoogleCart ( $merchant_id, $merchant_key, $server_type, $currency );
			
			foreach ( $cartList as $cartItem ) {
				$product = $cartItem->getProduct ();
				$item = new GoogleItem ( $product->getName (), // Item name
$product->getDescription (), // Item description
$cartItem->quantity, // Quantity
$product->price );
				$cart->AddItem ( $item );
			}
			
			// Add Shipping Rate
			//$shippingFeeSettingEntity = $this->settingsDataService->getItem(SETTINGS_SHIPPING_FEE, $this->ownerId);
			//$shipFee = floatval($shippingFeeSettingEntity->value);
			//$shippingMethodSettingEntity = $this->settingsDataService->getItem(SETTINGS_SHIPPING_METHOD, $this->ownerId);
			//$shipMethod = strval($shippingMethodSettingEntity->value);
			//echo "<pre>" . print_r($shippingMethod, true). "</pre>";
			//die();
			

			if ($shippingMethod) {
				$shipFee = floatval ( $shippingMethod->fee );
				$shipMethod = strval ( $shippingMethod->name );
				
				// Get Shipping Rate from configuration
				$ship = new GoogleFlatRateShipping ( $shipMethod, floatval ( $shipFee ) );
				$cart->AddShipping ( $ship );
			}
			
			// Get currency here
			$cart->currency = $this->currencyCode;
			
			// Add <merchant-private-data>
			$cart->SetMerchantPrivateData ( new MerchantPrivateData ( array ("merchant-order-id" => $orderId, "merchant-customer-id" => $customerId ) ) );
			
			// Edit Cart URL
			$editCartUrl = $this->getApplicationUrl () . "Product/shoppingCart";
			
			// Continue Buying
			$continueShopUrl = $this->getApplicationUrl () . "Product";
			
			$cart->SetEditCartUrl ( $editCartUrl );
			
			// Specify "Return to xyz" link
			$cart->SetContinueShoppingUrl ( $continueShopUrl );
			
			// This will do a server-2-server cart post and send an HTTP 302 redirect status
			// This is the best way to do it if implementing digital delivery
			// More info http://code.google.com/apis/checkout/developer/index.html#alternate_technique
			list ( $status, $error ) = $cart->CheckoutServer2Server ();
			
			if ($status != 200) {
				$this->isError = true;
				$this->error = $error;
			}
		}
	}
	
	/**
	 * Handle Paypal Payment Gateway
	 * @param array $cartList
	 * @param string $orderId
	 * @param string $customerId
	 * @param UserShipEntity $shippingMethod: Shipping Method
	 */
	private function handlePaypal($cartList, $orderId, $customerId, $shippingMethod) {
		// Normal Paypal
		$params ['return_url'] = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/index.php?authen=User&u=' . $this->ownerFullName . '&control=Product&action=returnPayment' . '&state=return&order_id=' . $orderId;
		$params ['cancel_url'] = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/index.php?authen=User&u=' . $this->ownerFullName . '&control=Product&action=returnPayment' . '&state=cancel&order_id=' . $orderId;
		$params ['notify_url'] = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/PaypalIpn/index';
		
		// Get Shipping Amount here
		$listItems = array ();
		$totalPrice = 0.0;
		if (! is_array ( $cartList ))
			return;
		
		foreach ( $cartList as $cartItem ) {
			$product = $cartItem->getProduct ();
			$item = array ();
			$item ['NAME'] = $product->getName ();
			$item ['DESC'] = $product->getDescription ();
			$item ['AMT'] = floatval ( $product->price );
			$item ['NUMBER'] = $orderId;
			$item ['QTY'] = $cartItem->quantity;
			$totalPrice += floatval ( $product->price ) * $cartItem->quantity;
			$listItems [] = $item;
		}
		
		$invoiceNum = md5 ( $orderId . $product->getName () );
		
		// Get Shipping Method and Shipping Fee
		$shipFee = 0;
		if ($shippingMethod) {
			$shipFee = floatval ( $shippingMethod->fee );
		}
		//$shippingFeeSettingEntity = $this->settingsDataService->getItem(SETTINGS_SHIPPING_FEE, $this->ownerId);
		$totals = floatval ( $shipFee ) + floatval ( $totalPrice );
		$params ['driverSpecificParams'] ['PayPal'] = array ('AMT' => floatval ( $totals ), 'CURRENCYCODE' => $this->currencyCode, 'DESC' => "", 'SHIPPINGAMT' => floatval ( $shipFee ), 'CUSTOM' => $customerId, 'INVNUM' => $invoiceNum, 'ITEMAMT' => floatval ( $totalPrice ), 'ITEMS' => $listItems );
		
		try {
			$paypalConfig = $this->settingsDataService->getPaypalSettings ( $this->ownerId );
			$paypalGateway = new PayPalGateway ( $paypalConfig );
			$paypalGateway->setConfig ( $paypalConfig );
			
			// Get GateWay URL
			$transactionUrl = $paypalGateway->getGatewayUrl ();
			$transaction = $paypalGateway->createTransaction ( $params );
			
			$transactionData = $transaction->getData ();
			// Handle redirection
			$transactionUrl .= '?cmd=_express-checkout&token=' . $transactionData ['token'];
			
			header ( "Location: " . $transactionUrl );
		} catch ( Exception $ex ) {
			echo $ex->getMessage ();
		}
	
	}
	
	public function returnPaymentAction() {
		$paypalConfig = $this->settingsDataService->getPaypalSettings ();
		$paypalGateway = new PayPalGateway ( $paypalConfig );
		$paypalGateway->setConfig ( $paypalConfig );
		
		$order_id = $_GET ['order_id'];
		$packageOrderEntity = $this->customerOrderDataService->getById ( $order_id );
		
		if (is_null ( $packageOrderEntity )) {
			$this->indexAction ();
			return;
		}
		
		try {
			$result = $paypalGateway->onTransactionReturn ( $packageOrderEntity, $_GET, $this->currencyCode );
			//echo $result;
			//die();
			if ($result == SUCC) {
				$packageOrderEntity->orders_status = ORDER_STATUS_PROCESSING;
				$this->customerOrderDataService->update ( $packageOrderEntity );
				$this->userCustomerBasketDataService->removeCart ( $this->authentication->getCurrentUserId (), NULL );
				
				$customerSession = $this->authentication->getCustomerOrderSession ();
				//Add Product Order Status History
				$orderStatusHistoryDataService = new OrderStatusHistoryDataService ();
				$orderHistory = $orderStatusHistoryDataService->beforeCreate ();
				$orderHistory->orders_id = $order_id;
				$orderHistory->orders_status = ORDER_STATUS_PROCESSING;
				$orderHistory->date_added = date ( "Y-m-d H:i:s" );
				$orderHistory->comments = "";
				$orderStatusHistoryDataService->create ( $orderHistory );
				
				//Clear the SESSION
				$customerSession->shippingAddressId = - 1;
				$customerSession->billingAddressId = - 1;
				$customerSession->comment = "";
				$this->authentication->saveCustomerOrderSession ( $customerSession );
				
				$url = $this->getApplicationUrl () . "Product/orderSuccess";
				CommonUtils::redirect ( $url );
				return - 1;
			} else {
				$url = $this->getApplicationUrl () . "Product/orderFail";
				CommonUtils::redirect ( $url );
				return - 1;
			}
		} catch ( ExceptionAbstract $ex ) {
			//echo $ex->getMessage();
			//die();
			

			$url = $this->getApplicationUrl () . "Product/orderFail";
			CommonUtils::redirect ( $url );
			return - 1;
		
		//echo $ex->getMessage();
		}
	
	}
	
	public function orderFailAction() {
		if ($this->isMobileMode == false) {
			// Assign Smarty Content
			$this->assignSmartyContent ( 'Product/checkout_fail.tpl' );
		} else {
			$this->assignSmartyMobileContent ( 'Product/m_checkout_fail.tpl' );
		}
	
		//$this->smarty->assign('SMARTY_CONTENT_PATH', 'template1/Product/checkout_success.tpl');
	//$this->smarty->display(APPLICATION_PATH . '/Layouts/template1/MainLayout.tpl');
	}
	
	/**
	 * Handle Eway payment gateway
	 * @param UserCustomerBasketEntity[] $cartList
	 * @param CustomerOrderEntity $order
	 * @param UserShipEntity $shippingMethod: Shipping Method
	 */
	protected function _handleEway($cartList, $order, $shippingMethod) {
		
		// Get Configuration
		$config = $this->settingsDataService->getEwaySettings ( $this->ownerId );
		if (! empty ( $config ['customerId'] ) && ! empty ( $config ['username'] ) && isset ( $config ['enable'] ) && $config ['enable'] == true) {
			
			$totalPrice = 0.0;
			foreach ( $cartList as $cartItem ) {
				$product = $cartItem->getProduct ();
				$totalPrice += floatval ( $product->price ) * $cartItem->quantity;
			}
			
			// Get Shipping Method and Shipping Fee
			//$shippingFeeSettingEntity = $this->settingsDataService->getItem(SETTINGS_SHIPPING_FEE, $this->ownerId);
			//$shipFee = floatval($shippingFeeSettingEntity->value);
			$shipFee = 0;
			if ($shippingMethod) {
				$shipFee = floatval ( $shippingMethod->fee );
			}
			$totals = floatval ( $shipFee ) + floatval ( $totalPrice );
			
			// Get first name and last name
			$name = $order->customers_name;
			$name = split ( " ", $name, 2 );
			$firstName = (! empty ( $name [0] )) ? $name [0] : "";
			$lastName = (! empty ( $name [1] )) ? $name [1] : "";
			
			// Cancel, Response URL
			$cancelURL = $this->getApplicationUrl () . "Product";
			$returnURL = $this->getApplicationUrl () . "Eway";
			
			// Post params
			$params = array ("CustomerID" => $config ['customerId'], "UserName" => $config ['username'], "Amount" => number_format ( $totals, 2 ), "Currency" => $this->currencyCode, "Language" => "EN", "CustomerFirstName" => $firstName, "CustomerLastName" => $lastName, "CustomerAddress" => $order->customers_street, "CustomerCity" => $order->customers_city, "CustomerState" => $order->customers_state, "CustomerPostCode" => $order->customers_postcode, "CustomerCountry" => $order->customers_country, "CustomerEmail" => $order->customers_email, "CustomerPhone" => $order->customers_telephone, "CancelURL" => $cancelURL, "ReturnUrl" => $returnURL, "ModifiableCustomerDetails" => "true", "MerchantReference" => $order->id );
			
			$config = $this->settingsDataService->getEwaySettings ( $this->ownerId );
			$geteway = new EwayGateway ( $config );
			$geteway->setConfig ( $config );
			$geteway->getGateway ()->getLogByName ( 'eway' )->log ( " \n eway payment ", Zend_Log::INFO );
			$geteway->getGateway ()->getLogByName ( 'eway' )->log ( " \n  params \n " . print_r ( $params, true ), Zend_Log::INFO );
			
			// $params = http_build_query($params);
			$params = http_build_query ( $params, '', '&' );
			$postURL = "https://payment.ewaygateway.com/Request/?$params";
			
			$geteway->getGateway ()->getLogByName ( 'eway' )->log ( " \n  posturl " . $postURL, Zend_Log::INFO );
			
			$ch = curl_init ();
			curl_setopt ( $ch, CURLOPT_URL, $postURL );
			curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
			curl_setopt ( $ch, CURLOPT_HEADER, 1 );
			curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
			
			if (defined ( 'CURL_PROXY_REQUIRED' ) && CURL_PROXY_REQUIRED == 'True') {
				$proxy_tunnel_flag = (defined ( 'CURL_PROXY_TUNNEL_FLAG' ) && strtoupper ( CURL_PROXY_TUNNEL_FLAG ) == 'FALSE') ? false : true;
				curl_setopt ( $ch, CURLOPT_HTTPPROXYTUNNEL, $proxy_tunnel_flag );
				curl_setopt ( $ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP );
				curl_setopt ( $ch, CURLOPT_PROXY, CURL_PROXY_SERVER_DETAILS );
			}
			$response = curl_exec ( $ch );
			
			$geteway->getGateway ()->getLogByName ( 'eway' )->log ( " \n  respone \n " . print_r ( $response, true ), Zend_Log::INFO );
			
			$responseMode = $this->_fetchEwayData ( $response, '<result>', '</result>' );
			$responseUrl = $this->_fetchEwayData ( $response, '<uri>', '</uri>' );
			
			$geteway->getGateway ()->getLogByName ( 'eway' )->log ( " \n  responseMode " . $responseMode, Zend_Log::INFO );
			$geteway->getGateway ()->getLogByName ( 'eway' )->log ( " \n  responseUrl " . $responseUrl, Zend_Log::INFO );
			
			if ($responseMode == "True") {
				header ( "location: " . $responseUrl );
				exit ();
			}
		
		}
	}
	
	/**
	 * Fetch response from Eway
	 * @param string $string
	 * @param string $start_tag
	 * @param string $end_tag
	 * @return string $fetch_data
	 */
	protected function _fetchEwayData($string, $start_tag, $end_tag) {
		$position = stripos ( $string, $start_tag );
		$str = substr ( $string, $position );
		$str_second = substr ( $str, strlen ( $start_tag ) );
		$second_positon = stripos ( $str_second, $end_tag );
		$str_third = substr ( $str_second, 0, $second_positon );
		$fetch_data = trim ( $str_third );
		return $fetch_data;
	}
	
	/**
	 * Create a form to submit 2 checkout
	 * @param UserCustomerBasketEntity[] $cartList
	 * @param CustomerOrderEntity $order
	 * @param UserShipEntity $shippingMethod: Shipping Method
	 */
	protected function _submit2Checkout($cartList, $order, $shippingMethod) {
		// Get Configuration
		$config = $this->settingsDataService->get2CheckoutSettings ( $this->ownerId );
		if (! empty ( $config ['vendor_id'] ) && isset ( $config ['testMode'] )) {
			
			$totalPrice = 0.0;
			foreach ( $cartList as $cartItem ) {
				$product = $cartItem->getProduct ();
				$totalPrice += floatval ( $product->price ) * $cartItem->quantity;
				$carts [] = $cartItem;
			}
			
			// Get Shipping Method and Shipping Fee
			//$shippingFeeSettingEntity = $this->settingsDataService->getItem(SETTINGS_SHIPPING_FEE, $this->ownerId);
			//$shipFee = floatval($shippingFeeSettingEntity->value);
			

			//Get Shipping Fee
			$shipFee = 0;
			if ($shippingMethod) {
				$shipFee = floatval ( $shippingMethod->fee );
			}
			$totals = floatval ( $shipFee ) + floatval ( $totalPrice );
			
			// Get current customer
			$usersDataService = new UsersDataService ();
			$currentCustomer = $usersDataService->getById ( $order->customers_id );
			
			// Return URL
			$returnURL = $this->getApplicationUrl () . "TwoCheckout";
			
			// Assign Values Data
			$this->smarty->assign ( 'totals', number_format ( $totals, 2 ) );
			$this->smarty->assign ( 'config', $config );
			$this->smarty->assign ( 'carts', $carts );
			$this->smarty->assign ( 'cartList', $cartList );
			$this->smarty->assign ( 'order', $order );
			$this->smarty->assign ( 'currentCustomer', $currentCustomer );
			$this->smarty->assign ( 'returnURL', $returnURL );
			
			// Assign Smarty Content
			if ($this->isMobileMode == false) {
				$this->assignSmartyContent ( 'Product/2checkout.tpl' );
			} else {
				$this->assignSmartyMobileContent ( 'Product/m_2checkout.tpl' );
			}
		}
	}
	
	/**
	 * View Customer Order Details
	 */
	public function orderInfoAction() {
		// Get Id of page
		$id = $this->getQuery ( 'id', 0 );
		
		if (! empty ( $id ) && is_numeric ( $id )) {
			
			$id = intval ( $id );
			
			//Get All Customer Order
			$customerOrderEntity = $this->customerOrderDataService->getById ( $id );
			$this->smarty->assign ( 'orderEntity', $customerOrderEntity );
			
			//Get shipping method
			$userShipDataService = new UserShipDataService ();
			$shippingMethod = $userShipDataService->getById ( $customerOrderEntity->shipping_method );
			$this->smarty->assign ( 'shippingMethod', $shippingMethod );
			
			//Get All
			$arrElement = array ();
			$arrElement ['orders_id'] = $id;
			$cartList = $this->customerOrderProductDataService->getItems ( $arrElement );
			
			$this->smarty->assign ( 'cartList', $cartList );
			
			$statusHistory = $this->orderStatusHistoyDataService->getItems ( $arrElement );
			$this->smarty->assign ( 'listStatus', $statusHistory );
		}
		
		// Assign Smarty Content
		if ($this->isMobileMode == false) {
			$this->assignSmartyContent ( 'MyAccount/order_info.tpl' );
		} else {
			$this->assignSmartyMobileContent ( 'MyAccount/m_order_info.tpl' );
		}
	
		//$this->smarty->assign('SMARTY_CONTENT_PATH', 'template1/MyAccount/order_info.tpl');
	//$this->smarty->display(APPLICATION_PATH . '/Layouts/template1/MainLayout.tpl');
	}

}
